const t = require("@babel/types");
const parser = require("@babel/parser");
const path = require("path");
const fs = require("fs");
const rd = require("rd");
const traverse = require("@babel/traverse").default;
const generate = require("@babel/generator").default;
const { validate } = require("jtd");
// 获得当前执行node命令时候的文件夹目录名
const commandPath = process.cwd();
let config = null;
// TODO: 读取 config 信息

const schema = {
  properties: {
    routePath: { type: "string" },
    fileName: { type: "string" },
  },
  optionalProperties: {
    menuOrder: {
      elements: { type: "string" },
    },
  },
};

// jtd.validate returns an array of validation errors. If there were no problems
// with the input, it returns an empty array.

// Outputs: []

try {
  config = require(path.resolve(commandPath, "./generate.config"));
} catch (error) {
  console.log("缺少了配置文件，请查看使用文档");
  process.exit();
}

console.log(validate(schema, config));
// TODO: 配置文件不存在则询问用户

// TODO: 读取 collection 下的所有文件信息

const routeRoot = path.isAbsolute(config.routePath)
  ? config.routePath
  : path.resolve(commandPath, "./example");

// TODO: 判断 collection 文件存在
const routeCollectionPath = path.resolve(commandPath, "./example/collection");

// 同步
const files = rd.readFileSync(routeCollectionPath);
const routes = files.map((filePath) => {
  return path.basename(filePath).replace(path.extname(filePath), "");
});

// TODO: 根据 config 里的重新排序

const templateCode = `
  export const routes = []

  export const menus = []
`;

const ast = parser.parse(templateCode, { sourceType: "module" });

traverse(ast, {
  Program(path) {
    const reversedRoutes = [...routes].reverse();
    const imports = reversedRoutes.forEach((name) => {
      path.node.body.unshift(
        t.importDeclaration(
          [t.importDefaultSpecifier(t.identifier(`${firstUpperCase(name)}`))],
          t.stringLiteral(`./${name}`)
        )
      );
    });
  },

  Identifier(path) {
    if (path.node.name === "routes") {
      if (t.isVariableDeclarator(path.container)) {
        // console.log(path.parent);
        routes.forEach((name) => {
          path.parent.init.elements.push(
            t.spreadElement(
              t.memberExpression(
                t.Identifier(`${firstUpperCase(name)}`),
                t.Identifier("routes")
              )
            )
          );
        });
      }
    }

    if (path.node.name === "menus") {
      if (t.isVariableDeclarator(path.container)) {
        // console.log(path.parent);
        routes.forEach((name) => {
          path.parent.init.elements.push(
            t.spreadElement(
              t.memberExpression(
                t.Identifier(`${firstUpperCase(name)}`),
                t.Identifier("menus")
              )
            )
          );
        });
      }
    }
  },
});

const result = generate(ast);

console.log(result.code);

// TODO: 写入到文件
fs.writeFileSync(path.resolve(routeRoot, "./index.js"), result.code, "utf8");

function firstUpperCase(str) {
  return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}
